package com.dispatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dispatcher.bean.Order;
import com.dispatcher.bean.UserOrders;
import com.dispatcher.common.OrderSort;
import com.dispatcher.common.OrderSort.UserOrdersSort;
import com.dispatcher.helper.SDHelper;
import com.dispatcher.http.HttpHelperWraper;
import com.dispatcher.http.HttpHelperWraper.HttpRequestParam;
import com.dispatcher.http.HttpHelperWraper.OnNetListener;
import com.dispatcher.view.PullRefreshHitMoreListView;
import com.dispatcher.view.PullRefreshHitMoreListView.OnRefreshRequestListener;
import com.zuzhili.database.CacheDataCtrl;
import com.zuzhili.database.CacheDataCtrl.CacheType;

public class OrderActivity extends ActivityBase implements OnNetListener, OnItemClickListener {
	private final String GET_UNPICK_ORDER = "getUnpickOrder";
	private final String PICK_ORDER = "pickOrder";
	private LayoutInflater mInflater;
	private List<UserOrders> userOrdersList;
	private OrderAdapter orderAdapter;
	private PullRefreshHitMoreListView  lvOrderList;
	
	private String presentid;
	private List<String> orderids;
	
	private int start = 0;
	private int count = 50;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);
		lvOrderList = (PullRefreshHitMoreListView) findViewById(R.id.lv_orderlist);
		orderAdapter = new OrderAdapter();
		userOrdersList = new ArrayList<UserOrders>();
		lvOrderList.setAdapter(orderAdapter);
		lvOrderList.setonRefreshListener(new OnRefreshRequestListener() {
			
			@Override
			public void onRefresh() {
				start = 0;
//				orderList.clear();
				lvOrderList.changeToOnRefresh();
				sendRequest(GET_UNPICK_ORDER, start);
			}
		});
		lvOrderList.setOnItemClickListener(this);
		presentid = SDHelper.getPresentId();
		lvOrderList.changeToOnRefresh();
		sendRequest(GET_UNPICK_ORDER, start);
		
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	void sendRequest(String action, int start) {
		HttpHelperWraper http = new HttpHelperWraper();
		HttpRequestParam param = http.getParam();
		makeparam(param, action, start);
		http.AsyncTaskWithCache(param);
	}
	
	void makeparam(HttpRequestParam param, String action, int start){
		if (param == null) {
			return;
		}
		param.ctx = this;
		param.listener = this;
		param.activitybase=this;
		param.cachetype=CacheDataCtrl.CacheType.UnPickOrders_Cache;
		param.identify="unpick";
		param.expiretime=0;
		HashMap<String, Object> requestparams = new HashMap<String, Object>();
		if(action.equals(GET_UNPICK_ORDER)) {
			requestparams.put("task", "getUnpickOrder");
			requestparams.put("begin", start + "");
			requestparams.put("count", count + "");
			
		} else if(action.equals(PICK_ORDER)) {
			requestparams.put("task", "pickOrder");
			requestparams.put("presentid", presentid);
			requestparams.put("orders", JSON.toJSONString(orderids));
			
		}
		param.nodesrequest = requestparams;
	}
	
	@Override
	public void onNetSuccess(HttpRequestParam param) {
		Log.i("liutao", param.nodesrequest.toString());
		if(param.nodesrequest.get("task").equals("pickOrder")) {
			HttpHelperWraper http = new HttpHelperWraper();
			http.clearCache(this, CacheType.UnPickOrders_Cache, "unpick");
			return;
		}
		
//		JSONObject nodesresult = param.nodesresult;
//		JSONArray jsonArray = null;
//		if(nodesresult.has("list")) {
//			try {
//				jsonArray = (JSONArray) nodesresult.get("list");
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
//		}
		com.alibaba.fastjson.JSONObject obrst=JSON.parseObject(param.jsonstr);
		
		List<UserOrders> l = JSON.parseArray(obrst.getString("list"), UserOrders.class);
		if(param.nodesrequest.get("begin").equals("0")){
			userOrdersList.clear();
			
		}
		userOrdersList.addAll(l);
		Collections.sort(userOrdersList, new OrderSort().getUserOrdersSort());
		orderAdapter.notifyDataSetChanged();
		
		start += count;
		if(param.bendreq) {
			lvOrderList.onPullRefreshEnd();
			
			if (l.size() == 0) {
				Toast.makeText(getApplicationContext(), "没有更多了",
						Toast.LENGTH_SHORT).show();
				lvOrderList.onFooterRefreshEnd(true);
				lvOrderList.onFooterHide();
			} else {
				lvOrderList.onFooterRefreshEnd(false);
			}
			
		}
		
	}

	@Override
	public void onNetError(HttpRequestParam param) {
		Toast.makeText(this, param.rstmsg, 2000).show();
	}

	OnClickListener leftlis = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
		}
	};
	
	OnClickListener rightlis = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
		}
	};
	
	public class OrderAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return userOrdersList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return userOrdersList.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.order_item, null);
				holder.homeRegion = (TextView) convertView
						.findViewById(R.id.tv_home_region);

//				holder.count = (TextView) convertView
//						.findViewById(R.id.tv_count);
				holder.goodsName = (TextView) convertView.findViewById(R.id.tv_goods_name);
//				holder.address = (TextView) convertView
//						.findViewById(R.id.tv_address);
				holder.pickOrder = (Button) convertView.findViewById(R.id.bt);
//				holder.unitNo = (TextView) convertView.findViewById(R.id.tv_unit_no);
//				holder.buildingNo = (TextView) convertView.findViewById(R.id.tv_building_no);
				holder.phone = (TextView) convertView.findViewById(R.id.tv_phone);
				holder.needpay = (TextView) convertView.findViewById(R.id.tv_needpay);
				holder.time = (TextView) convertView.findViewById(R.id.tv_time);
				
				holder.pickOrder.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						orderids = new ArrayList<String>();
						
						for(Order ord : userOrdersList.get(pos).getOrders()){
							orderids.add(ord.getOrderid());
						}
						userOrdersList.remove(pos);
						orderAdapter.notifyDataSetChanged();
						sendRequest(PICK_ORDER, 0);
					}
					
				});
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			UserOrders userorders = userOrdersList.get(position);
//			holder.needpay.setText(order.getNeedpay());
			String name="";
			for(Order ord:userorders.getOrders()){
				name+=ord.getName()+" "+ord.getGoodtype()+" X "+ord.getCount()+"\n";
			}
			holder.goodsName.setText(name);
			holder.time.setText(userorders.getTime());
			
			holder.homeRegion.setText(userorders.getRegion()+" "+userorders.getName());
			holder.phone.setText(userorders.getPhone());
			holder.pickOrder.setText("领取订单");
			
			return convertView;
		}
		
	}
	
	class ViewHolder {
		TextView homeRegion;
		TextView unitNo;
		TextView buildingNo;
		TextView count;
		TextView needpay;
		TextView goodsName;
		TextView address;
		TextView phone;
		Button pickOrder;
		TextView time;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
		if(pos == arg0.getCount() - 1) {
			if (lvOrderList.onFooterRefreshBegin()) {
				sendRequest(GET_UNPICK_ORDER, start);
			}
		}
	}
}
